import React from 'react';
import { PageLoading } from '@ant-design/pro-layout';
import { Redirect, connect, ConnectProps } from 'umi';
import { stringify } from 'querystring';
import { ConnectState } from '@/models/connect';
import { CurrentUser } from '@/models/user';
import { MenuItem } from '@/models/menu';

interface SecurityLayoutProps extends ConnectProps {
  loading?: boolean;
  currentUser?: CurrentUser;
  menuList: Array<MenuItem>;
}

interface SecurityLayoutState {
  isReady: boolean;
}

class SecurityLayout extends React.Component<SecurityLayoutProps, SecurityLayoutState> {
  state: SecurityLayoutState = {
    isReady: false,
  };

  async componentDidMount() {
    const { dispatch } = this.props;

    if (dispatch) {
      //获得当前用户信息
      dispatch({
        type: 'user/fetchCurrent',
        callback: () => {
          // this.setState({
          //   isReady: true,
          // });
        },
      });
    }

    /* 获取用户的目录 */
    await this.initMenu(dispatch);
    // 异步处理，获得菜单后再设置isReady，确保后续菜单可以先加载到数据
    this.setState({
      isReady: true,
    });
  }

  initMenu = async (dispatch: any) => {
    await dispatch({
      type: 'menus/fetchMenu',
    });
  };

  render() {
    const { isReady } = this.state;
    const { children, loading, currentUser } = this.props;
    // You can replace it to your authentication rule (such as check token exists)
    // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）
    // console.log(JSON.stringify(currentUser));
    const isLogin = currentUser && currentUser.id;
    const queryString = stringify({
      redirect: window.location.href,
    });
    if ((!isLogin && loading) || !isReady) {
      return <PageLoading />;
    }
    if (!isLogin) {
      return <Redirect to={`/user/login?${queryString}`} />;
    }
    return children;
  }
}

export default connect(({ user, loading }: ConnectState) => ({
  currentUser: user.currentUser,
  loading: loading.models.user,
}))(SecurityLayout);
